﻿//-----------------------------------------------------------------------
// <copyright file="MessageFactory.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Microsoft.Live.Messenger
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;

    internal sealed class MessageFactory
    {
        private readonly Dictionary<MessengerEntity, Message> messages = new Dictionary<MessengerEntity, Message>();

        private readonly User user;

        public MessageFactory(User user)
        {
            this.user = user;
        }

        public Message FindOrCreate(object obj)
        {
            if (obj == null)
            {
                return null;
            }

            return FindOrCreate(new MessengerEntity(obj));
        }

        public Message FindOrCreate(MessengerEntity entity)
        {
            Message message = null;

            if (this.messages.TryGetValue(entity, out message))
            {
                return message;
            }

            MessageType type = entity.GetEnumProperty<MessageType>("Type");

            switch (type)
            {
                case MessageType.TextMessage:
                    message = new TextMessage(entity);
                    break;
                case MessageType.NudgeMessage:
                    message = new NudgeMessage(entity);
                    break;
                case MessageType.ApplicationMessage:
                    throw new NotImplementedException();
                default:
                    Debug.Assert(false, "Unexpected message type.");
                    break;
            }

            if (message != null)
            {
                message.Sender = this.user.IMAddressFactory.FindOrCreate(entity.GetProperty("Sender"));

                this.messages.Add(message.Entity, message);
            }

            return message;
        }

        public void Add(Message message)
        {
            Message existing = null;

            if (!this.messages.TryGetValue(message.Entity, out existing))
            {
                this.messages.Add(message.Entity, message);
            }
        }
    }
}